package com.ruoyi.point.service.impl;

import java.time.Duration;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.data.redis.core.RedisTemplate;
import com.ruoyi.point.mapper.PointFlowMapper;
import com.ruoyi.point.domain.PointFlow;
import com.ruoyi.point.service.IPointFlowService;

/**
 * 积分流水Service业务层处理
 * 
 * @author hy
 * @date 2025-08-12
 */
@Service
public class PointFlowServiceImpl implements IPointFlowService 
{
    @Autowired
    @Qualifier("pointFlowMapper1")
    private PointFlowMapper pointFlowMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // 缓存常量
    private static final String POINT_FLOW_DETAIL_KEY = "point_flow:detail:";
    private static final String POINT_FLOW_USER_STATS_KEY = "point_flow:user_stats:";
    private static final String POINT_FLOW_MONTH_STATS_KEY = "point_flow:month_stats:";
    private static final Duration POINT_FLOW_DETAIL_EXPIRE = Duration.ofMinutes(20);
    private static final Duration POINT_FLOW_STATS_EXPIRE = Duration.ofMinutes(10);

    /**
     * 查询积分流水
     * 
     * @param id 积分流水主键
     * @return 积分流水
     */
    @Override
    public PointFlow selectPointFlowById(Long id)
    {
        return pointFlowMapper.selectPointFlowById(id);
    }

    /**
     * 查询积分流水列表
     * 
     * @param pointFlow 积分流水
     * @return 积分流水
     */
    @Override
    public List<PointFlow> selectPointFlowList(PointFlow pointFlow)
    {
        return pointFlowMapper.selectPointFlowList(pointFlow);
    }

    /**
     * 新增积分流水
     * 
     * @param pointFlow 积分流水
     * @return 结果
     */
    @Override
    public int insertPointFlow(PointFlow pointFlow)
    {
        int result = pointFlowMapper.insertPointFlow(pointFlow);
        if (result > 0) {
            // 清除相关缓存
            clearPointFlowCache(pointFlow.getUserId());
        }
        return result;
    }

    /**
     * 修改积分流水
     * 
     * @param pointFlow 积分流水
     * @return 结果
     */
    @Override
    public int updatePointFlow(PointFlow pointFlow)
    {
        int result = pointFlowMapper.updatePointFlow(pointFlow);
        if (result > 0) {
            // 清除相关缓存
            clearPointFlowCache(pointFlow.getUserId());
        }
        return result;
    }

    /**
     * 批量删除积分流水
     * 
     * @param ids 需要删除的积分流水主键集合
     * @return 结果
     */
    @Override
    public int deletePointFlowByIds(Long[] ids)
    {
        int result = pointFlowMapper.deletePointFlowByIds(ids);
        if (result > 0) {
            // 清除相关缓存
            clearAllPointFlowCache();
        }
        return result;
    }

    /**
     * 删除积分流水信息
     * 
     * @param id 积分流水主键
     * @return 结果
     */
    @Override
    public int deletePointFlowById(Long id)
    {
        int result = pointFlowMapper.deletePointFlowById(id);
        if (result > 0) {
            // 清除相关缓存
            clearAllPointFlowCache();
        }
        return result;
    }

    /**
     * 查询用户积分明细列表（多表联查）
     * 
     * @param userId 用户ID
     * @return 积分明细列表
     */
    @Override
    public List<PointFlow> selectPointFlowDetailByUserId(Long userId)
    {
        String cacheKey = POINT_FLOW_DETAIL_KEY + userId;
        
        // 尝试从缓存获取
        List<PointFlow> cached = (List<PointFlow>) redisTemplate.opsForValue().get(cacheKey);
        if (cached != null) {
            return cached;
        }
        
        // 从数据库查询
        List<PointFlow> result = pointFlowMapper.selectPointFlowDetailByUserId(userId);
        if (result != null && !result.isEmpty()) {
            // 存入缓存
            redisTemplate.opsForValue().set(cacheKey, result, POINT_FLOW_DETAIL_EXPIRE);
        }
        
        return result;
    }

    /**
     * 查询积分明细列表（多表联查，支持分页和筛选）
     * 
     * @param pointFlow 查询条件
     * @return 积分明细列表
     */
    @Override
    public List<PointFlow> selectPointFlowDetailList(PointFlow pointFlow)
    {
        return pointFlowMapper.selectPointFlowDetailList(pointFlow);
    }

    /**
     * 查询用户积分统计信息
     * 
     * @param userId 用户ID
     * @return 积分统计信息
     */
    @Override
    public Map<String, Object> selectUserPointStats(Long userId)
    {
        String cacheKey = POINT_FLOW_USER_STATS_KEY + userId;
        
        // 尝试从缓存获取
        Map<String, Object> cached = (Map<String, Object>) redisTemplate.opsForValue().get(cacheKey);
        if (cached != null) {
            return cached;
        }
        
        // 从数据库查询
        Map<String, Object> result = pointFlowMapper.selectUserPointStats(userId);
        if (result != null && !result.isEmpty()) {
            // 存入缓存
            redisTemplate.opsForValue().set(cacheKey, result, POINT_FLOW_STATS_EXPIRE);
        }
        
        return result;
    }

    /**
     * 查询用户本月积分统计
     * 
     * @param userId 用户ID
     * @return 本月积分统计
     */
    @Override
    public Map<String, Object> selectUserMonthPointStats(Long userId)
    {
        String cacheKey = POINT_FLOW_MONTH_STATS_KEY + userId;
        
        // 尝试从缓存获取
        Map<String, Object> cached = (Map<String, Object>) redisTemplate.opsForValue().get(cacheKey);
        if (cached != null) {
            return cached;
        }
        
        // 从数据库查询
        Map<String, Object> result = pointFlowMapper.selectUserMonthPointStats(userId);
        if (result != null && !result.isEmpty()) {
            // 存入缓存
            redisTemplate.opsForValue().set(cacheKey, result, POINT_FLOW_STATS_EXPIRE);
        }
        
        return result;
    }

    /**
     * 查询积分流水完整信息列表（完整多表联查，支持分页和筛选）
     * 
     * @param pointFlow 查询条件
     * @return 积分流水完整信息列表
     */
    @Override
    public List<PointFlow> selectPointFlowCompleteList(PointFlow pointFlow)
    {
        return pointFlowMapper.selectPointFlowCompleteList(pointFlow);
    }

    /**
     * 查询积分流水完整信息列表（优化版本，解决数据查询不完整问题）
     * 
     * @param pointFlow 查询条件
     * @return 积分流水完整信息列表
     */
    @Override
    public List<PointFlow> selectPointFlowCompleteListOptimized(PointFlow pointFlow)
    {
        return pointFlowMapper.selectPointFlowCompleteListOptimized(pointFlow);
    }

    /**
     * 查询用户积分流水完整信息（完整多表联查）
     * 
     * @param userId 用户ID
     * @return 积分流水完整信息列表
     */
    @Override
    public List<PointFlow> selectUserPointFlowComplete(Long userId)
    {
        String cacheKey = POINT_FLOW_DETAIL_KEY + "complete:" + userId;
        
        // 尝试从缓存获取
        List<PointFlow> cached = (List<PointFlow>) redisTemplate.opsForValue().get(cacheKey);
        if (cached != null) {
            return cached;
        }
        
        // 从数据库查询
        List<PointFlow> result = pointFlowMapper.selectUserPointFlowComplete(userId);
        if (result != null && !result.isEmpty()) {
            // 存入缓存
            redisTemplate.opsForValue().set(cacheKey, result, POINT_FLOW_DETAIL_EXPIRE);
        }
        
        return result;
    }

    /**
     * 根据积分规则类型查询相关流水（完整多表联查）
     * 
     * @param ruleType 规则类型
     * @return 积分流水完整信息列表
     */
    @Override
    public List<PointFlow> selectPointFlowByRuleType(String ruleType)
    {
        return pointFlowMapper.selectPointFlowByRuleType(ruleType);
    }

    /**
     * 查询积分流水完整信息（包含所有关联数据）
     * 
     * @param userId 用户ID
     * @return 积分流水完整信息列表
     */
    @Override
    public List<PointFlow> selectPointFlowCompleteInfo(Long userId)
    {
        String cacheKey = POINT_FLOW_DETAIL_KEY + "complete_info:" + userId;
        
        // 尝试从缓存获取
        List<PointFlow> cached = (List<PointFlow>) redisTemplate.opsForValue().get(cacheKey);
        if (cached != null) {
            return cached;
        }
        
        // 从数据库查询
        List<PointFlow> result = pointFlowMapper.selectPointFlowCompleteInfo(userId);
        if (result != null && !result.isEmpty()) {
            // 存入缓存
            redisTemplate.opsForValue().set(cacheKey, result, POINT_FLOW_DETAIL_EXPIRE);
        }
        
        return result;
    }

    /**
     * 根据积分流水ID查询完整信息（包含所有关联数据）
     * 
     * @param id 积分流水ID
     * @return 积分流水完整信息
     */
    @Override
    public PointFlow selectPointFlowWithAllRelations(Long id)
    {
        return pointFlowMapper.selectPointFlowWithAllRelations(id);
    }

    /**
     * 查询积分流水基础信息列表（最简化版本，确保返回所有数据）
     * 
     * @param pointFlow 查询条件
     * @return 积分流水基础信息列表
     */
    @Override
    public List<PointFlow> selectPointFlowBasicList(PointFlow pointFlow)
    {
        return pointFlowMapper.selectPointFlowBasicList(pointFlow);
    }

    /**
     * 清除用户积分流水缓存
     */
    private void clearPointFlowCache(Long userId) {
        if (userId != null) {
            redisTemplate.delete(POINT_FLOW_DETAIL_KEY + userId);
            redisTemplate.delete(POINT_FLOW_USER_STATS_KEY + userId);
            redisTemplate.delete(POINT_FLOW_MONTH_STATS_KEY + userId);
        }
    }

    /**
     * 清除所有积分流水缓存
     */
    private void clearAllPointFlowCache() {
        // 清除所有相关缓存
        redisTemplate.delete(POINT_FLOW_DETAIL_KEY + "*");
        redisTemplate.delete(POINT_FLOW_USER_STATS_KEY + "*");
        redisTemplate.delete(POINT_FLOW_MONTH_STATS_KEY + "*");
    }
}
